package cn.dapeng.rpc.common.codec;

import cn.dapeng.rpc.common.RpcResponse;
import cn.dapeng.rpc.common.serial.SerializeFactory;
import cn.dapeng.rpc.common.util.MagicNumberUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ClientByteToMessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        while (byteBuf.readableBytes() > 0) {
            int magicNum = byteBuf.getInt(byteBuf.readerIndex());
            int serialType = MagicNumberUtil.getSerialVersion(magicNum);
            int bodyLen = MagicNumberUtil.getBodyLen(magicNum);

            if (byteBuf.readableBytes() >= (bodyLen + Integer.BYTES)) {
                byteBuf.readBytes(Integer.BYTES);
                byte[] body = new byte[bodyLen];
                byteBuf.readBytes(body);

                RpcResponse response = SerializeFactory.deseria(body, RpcResponse.class, serialType);
                list.add(response);
            } else {
                break;
            }
        }
    }

}
